<?php
namespace App\Common;

use PhalApi\Logger;

/**
 * @name 日志记录：系统错误日志、mysql日志、短信及推送日志等
 * @author CabbageRun 2017-11-15
 * 
 */
class MyLogger extends Logger
{
    /** 外部传参 **/
    protected $logFolder;
    protected $dateFormat;

    /** 内部状态 **/
    protected $fileDate;
    protected $logFile;

    public function __construct($logFolder, $level, $dateFormat = 'Y-m-d H:i:s')
    {
        $this->logFolder = $logFolder;
        $this->dateFormat = $dateFormat;
        parent::__construct($level);
    }

    /**
     * 初始化：新建日记文件
     * {@inheritDoc}
     * @see \PhalApi\Logger\FileLogger::init()
     */
    protected function _init($dir)
    {
        if(! $dir){
            return;
        }
        // 跨天时新建日记文件
        $this->fileDate = date('Ymd', time());
        // 每月一个目录
        $folder = $this->logFolder . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . substr($this->fileDate, 0, -2);
        if(! file_exists($folder)){
            mkdir($folder . '/', 0777, TRUE);
        }
        // 每天一个文件
        $this->logFile = $folder . DIRECTORY_SEPARATOR . $this->fileDate . '.log';
        if(! file_exists($this->logFile)){
            // 当没有权限时，touch会抛出(Permission denied)异常
            @touch($this->logFile);
            // touch失败时，chmod会抛出(No such file or directory)异常
            if(file_exists($this->logFile)){
                chmod($this->logFile, 0777);
            }
        }
    }

    /**
     * 写入日志
     * @param unknown $msg
     * @param unknown $data
     */
    protected function _write($type, $msg, $data = null)
    {
        $msgArr = array();
        $msgArr['timeline'] = date($this->dateFormat, time());
        $msgArr['type'] = strtoupper($type);
        $msgArr['message'] = str_replace(PHP_EOL, '\n', $msg);
        if($data !== null){
            $msgArr['data'] = $data;
        }
        file_put_contents($this->logFile, print_r($msgArr, true) . PHP_EOL, FILE_APPEND);
    }

    /**
     * 记录日志
     * @param unknown $type
     * @param unknown $msg
     * @param unknown $data
     */
    public function log($type, $msg, $data = null)
    {
        $type = strtolower($type);
        switch($type){
            case 'info'://应用产品级日志
                $dir = 'info';
            break;
            case 'debug'://开发调试级日志
                $dir = 'debug';
            break;
            case 'error'://系统错误日志
                $dir = 'error';
            break;
            case 'sms'://短信日志
                $dir = 'sms';
            break;
            case 'push'://推送日志
                $dir = 'push';
            break;
            case 'slow'://慢查询日志
                $dir = 'slow';
            break;
            default:
                return;
            break;
        }
        $this->_init($dir);
        $this->_write($type, $msg.$this->logFile, $data);
    }
}
